//
//  QCOAuthViewModel.swift
//  SwiftDemoWithSina
//
//  Created by qu on 2017/2/4.
//  Copyright © 2017年 Apple. All rights reserved.
//

import UIKit

/*ViewModel作用:
   帮助控制器请求数据
   保存用户模型和提供数据给其他控制器
 */
class QCOAuthViewModel: NSObject {
  
    //全局访问点
    static let shared:QCOAuthViewModel = QCOAuthViewModel()
    //获取路径
    let file = (NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last! as NSString).appendingPathComponent("userAccount.archiver")
    
    
    //个人信息对象
    var userAccountModel:QCUserAccountModel?
    //访问令牌
    var accessToken: String?{
        if userAccountModel?.expires_Date?.compare(Date()) == ComparisonResult.orderedDescending {
            return userAccountModel?.access_token
        } else {
            
            return nil
        }
    }
    //判断用户是否登录
    var isLogin: Bool {
        //accessToken 有值就代表登录  反之就是没有登录
        return accessToken != nil
    }
    //重写init方法
    override init(){
        super.init()
        userAccountModel = getUserAccountModel()
    }
    
}

extension QCOAuthViewModel{
    //保存模型
    func saveUserAccountModel(userAccountModel:QCUserAccountModel){
        
        self.userAccountModel = userAccountModel
        //归档
        NSKeyedArchiver.archiveRootObject(userAccountModel, toFile: file)
    }
    
    //获取模型
    func getUserAccountModel() -> QCUserAccountModel?{
        //解档
   let userAccountModel = NSKeyedUnarchiver.unarchiveObject(withFile: file)as?QCUserAccountModel
        return userAccountModel
    }
}

extension QCOAuthViewModel{
    //请求获取accessToken
    func getUserAccount(code:String, isFinish:@escaping (Bool)->()){
      QCNetworkTools.shared.loadUserAccount(code: code, success: { (response)->() in
        guard let res = response as? [String: Any] else {
            isFinish(false)
            return
        }
      let userAccountModel = QCUserAccountModel.yy_model(withJSON: res)
        
        guard let u = userAccountModel else {
            isFinish(false)
            return
        }
        self.getUserInfo(userAccountModel: u, isFinish: isFinish)
      }, failure: { (error)->() in
        print("失败",error)
        isFinish(false)
      
      })
        
    }
    func getUserInfo(userAccountModel:QCUserAccountModel,isFinish:@escaping (Bool)->()){
     QCNetworkTools.shared.loadUserInfo(userAccountModel: userAccountModel, success: { (response) in
        guard let res = response as? [String: Any] else {
            isFinish(false)
            return
        }
        //赋值
        userAccountModel.screen_name = res["screen_name"]as? String
        userAccountModel.avatar_large = res["avatar_large"]as? String
        //保存用户模型
        self.saveUserAccountModel(userAccountModel: userAccountModel)
        isFinish(true)
        
     },failure:{ (error) in
        print("错误",error)
        isFinish(false)
        })
    }
}
